package com.gmall.order.service;

import com.gmall.coupon.feign.CouponApiFeignClient;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class RabbitMQServive_UnPay {

    @Autowired
    private CouponApiFeignClient couponApiFeignClient;
    @RabbitHandler
    @RabbitListener(queues = "Queue_UnPay_Delay")
    public void receive_30min(Channel channal, Message message,Long orderId) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {

            //1、查询订单状态 如果未支付，改为已关闭 接口1：根据订单ID查询订单
            //select *,order_status,userid from order_info where order_id = #{orderId};
            //order_status = PAID 如果已支付，什么都不做 return
            //else
            //接口2：修改订单状态
            //update order_info set order_status = CLOSED where order_id = orderId and order_status=UNPAID;
            //UNPAID("未支付"),
            //PAID("已支付" ),
            //WAITING_DELEVER("待发货"),
            //DELEVERED("已发货"),
            //CLOSED("已关闭"),
            //FINISHED("已完结") ,
            //SPLIT("订单已拆分");
            //2、优惠券退回去
            //NOT_USED("未使用"),
            //    USE_RUN("使用中" ),
            //    USED("已使用");
            // select * from coupon_use where order_id = #{orderId}
            //              and user_id = #{userid} and coupon_status = USE_RUN;

            //update 接口3：退回优惠卷
            /*coupon_use set coupon_status = NOT_USED,order_id = null,using_time = null
             where order_id = #{orderId} and coupon_status = USE_RUN*/
            couponApiFeignClient.unUseCoupon(orderId);

            channal.basicAck(deliveryTag, false);//手动确认，告诉MQ，我收到了，你可以删掉
        }catch (Exception e){
            e.printStackTrace();
            try {
                channal.basicNack(deliveryTag,false,true);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

}
